<?php
namespace frontend\controllers;

use yii;
use Faker\Provider\zh_TW\Address;
use common\components\Myhelpers;
use common\models\Order;
use common\models\Pay;
use common\models\User;
use common\models\Fund;
use common\models\Recharge;
use common\models\Product;
use common\models\ShoppingCart;
use common\models\Region;
use common\models\Shipping;
use common\models\Systemconfig;
use common\components\alipay\Alipay;

class OrderController extends FController
{
    public $alipay_config;

    public function init()
    {
        parent::init();
        
        $config = Systemconfig::getConfigValue('alipay');

        $this->alipay_config = [
            // 支付完成异步通知调用地址
            'notify_url' => "http://".$_SERVER['HTTP_HOST']."/paynotify",
            // 支付完成同步返回地址
            'return_url' => "http://".$_SERVER['HTTP_HOST']."/order/payreturn",
            // 支付宝商家 ID
            'partner'      => $config['alipay_pid'],
            // 支付宝商家 KEY
            'key'          => $config['alipay_wap_key'],
            // 支付宝商家注册邮箱
            'seller_email' => $config['alipay_seller_email']
        ];
    }

    //订单中心
    public function actionIndex(){
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
        $this->layout = "left.php";

        $uid = Yii::$app->user->id;

        //订单状态筛选条件
        $pay_status = (int)Yii::$app->request->get('s');
        
        $sta_where = "a.user_id = ".$uid;

        if($pay_status){
            $sta_where .= " AND a.order_status = ".$pay_status;
        }
        //订单状态统计
        for ($i=1; $i <6 ; $i++) { 
            $num = (new \Yii\db\Query())
                    ->select('count(id)')
                    ->from('order')
                    ->where(['user_id'=>$uid,'order_status'=>$i])
                    ->scalar();
            $count[$i]['num'] = $num;
            $count[$i]['name'] = Order::itemAlias('order_status',$i);
        }

        //默认显示全部订单//查询订单信息
        $order = (new \Yii\db\Query())
                ->from('order a')
                ->select('a.order_status,a.id,a.pay_fee,a.shipping_fee,a.create_time,b.name')
                ->where($sta_where)
                ->orderBy('id desc')
                ->leftJoin('address b','b.id = a.address_id')
                ->all();
        foreach ($order as $k => $v) {
            $prolist = (new \Yii\db\Query())
                    ->from('order_product a')
                    ->select('b.id,b.name,b.title,b.img_url,a.*')
                    ->where(['a.order_id' => $v['id']])
                    ->leftJoin('product AS b','a.product_id = b.id')
                    ->all();
            $order[$k]['list'] = $prolist;
        }
        /*var_dump($order);
        exit;*/

        return $this->render('index',[
            'order' => $order,
            'count' => $count,
        ]);
    }

    //订单详情页面
    public function actionView(){
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
        $uid = Yii::$app->user->id;

        //取消订单的操作
        $cancel_id = Myhelpers::RemoveXSS(Yii::$app->request->post('order_id'));

        if($cancel_id){
            $res = Yii::$app->db->createCommand()
                 ->update('order', ['order_status'=>5],'id = '.$cancel_id)
                 ->execute();
            return $res;
        }
        //url里面传过来的订单编号过滤一下
        $oid = Myhelpers::RemoveXSS(Yii::$app->request->get('id'));

        //默认显示全部订单//查询订单信息
        $detail = (new \Yii\db\Query())
                ->from('order a')
                ->select('a.*,b.name,b.province,b.city,b.district,b.address_detail,b.phone')
                ->where(['a.user_id'=>$uid,'a.id'=>$oid])
                ->leftJoin('address b','b.id = a.address_id')
                ->one();
        if(!$detail){
            exit("Order does not exist");
        }
               
        $prolist = (new \Yii\db\Query())
                ->from('order_product a')
                ->select('b.id,b.name,b.title,b.img_url,a.*')
                ->where(['a.order_id' => $oid])
                ->leftJoin('product AS b','a.product_id = b.id')
                ->all();
        if($detail['shipping_id']){
            $detail['shipping_id'] = Shipping::findOne($detail['shipping_id'])->shipping_name;
        }
        $detail['list'] = $prolist;
        if($detail['province']){
            $detail['province'] = Region::findOne($detail['province'])->name;
            $detail['city'] = Region::findOne($detail['city'])->name;
            $detail['district'] = Region::findOne($detail['district'])->name;
        }else{
            exit("Order's address does not exist");
        }
        


        return $this->render('detail',[
            'order' => $detail
        ]);
    }

    /**
     * @desc 确认订单
     */
    public function actionConfirm(){

        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
        $add_id = Myhelpers::RemoveXSS(Yii::$app->request->post('add_id'));
        if($add_id){
            $il = \common\models\Address::find()->where(['id'=>$add_id])->asArray()->one();
            $il['city_list'] = Region::find()->select('id,name')
                    ->where(['parent_id'=>$il['province'],'level'=>2])->asArray()->all();
            $il['dis_list'] = Region::find()->select('id,name')
                    ->where(['parent_id'=>$il['city'],'level'=>3])->asArray()->all();

            return json_encode($il);
        }

        $user_id = Yii::$app->user->id;
        $db = Yii::$app->db;
        $cache = Yii::$app->cache;//缓存
        $ids = Yii::$app->request->get('ids')?Yii::$app->request->get('ids'):Yii::$app->request->post('ids');//购物车id
        $ids = Myhelpers::RemoveXSS($ids);
        $ids = trim($ids, '-');
        $ids = str_replace('-', ',', $ids);

        //获取选取的购物车的商品
        $shopping_carts = ShoppingCart::find()->where("user_id=:user_id AND id IN(".$ids.")", [':user_id'=>$user_id])->orderBy('id DESC')->all();
        
        foreach ($shopping_carts as $k => $v) {
            $shopping_carts[$k]->price_unit = Product::find()->select('price_unit')->where(['id' => $v->product_id])->scalar();
        }
        if( !$shopping_carts ){
            return $this->redirect('/');die;//购物车没有商品，直接跳首页
        }

        if( Yii::$app->request->isAjax ){
            $rs = array('errNo' => 0, 'msg' => 'success');

            $address_id = (int)Yii::$app->request->post('address_id');
            $message = Myhelpers::RemoveXSS(Yii::$app->request->post('message'));

            do{
                //验证收货地址是否存在
                $address = \common\models\Address::find()->where('is_show=1 AND is_default=1 AND user_id=:user_id AND id=:id', [':user_id'=>$user_id, ':id'=>$address_id])->one();
                if( !$address ){
                    $rs = array('errNo' => 1, 'msg' => '收货地址不存在');
                    exit(json_encode($rs));
                }

                //验证购物车里的商品库存是否足够
                $product_data = '';//初始化拼凑的商品订单数据
                $order_id = 'order_id';//初始化订单id
                $product_fee = 0;//初始化商品的总价
                foreach( $shopping_carts as $v ){
                    $product = Product::find()->where('is_show=1 AND id=:id', [':id'=>$v->product_id])->one();
                    if( !$product ){
                        $rs = array('errNo' => 2, 'msg' => '商品：'.$v->title.' 已下架');
                        exit(json_encode($rs));
                    }
                    if( $product->stock<$v->product_num ){
                        $rs = array('errNo' => 3, 'msg' => '商品：'.$v->title.' 库存不足');
                        exit(json_encode($rs));
                    }
                    $v_total_price = $v->product_price * $v->product_num;//此件商品的总价
                    //拼凑商品订单数据
                    $product_data .= "(".$order_id.",".$v->product_id.",".$v->product_num.",".$v->product_price.",".$v_total_price."),";
                    //计算商品总价
                    $product_fee = bcadd($product_fee, $v_total_price, 2);
                }

                //绑定事务操作
                $transact=Yii::$app->db->beginTransaction();
                try{
                    $now_time = date('Y-m-d H:i:s');
                    $order_id = Myhelpers::getOrderID(80);//生成订单id

                    //添加订单商品数据
                    $product_data = trim($product_data, ',');
                    $product_data = str_replace('order_id', $order_id, $product_data);
                    $sql = "INSERT INTO `order_product` (`order_id`,`product_id`,`product_num`,`price`,`total_price`) VALUES $product_data";
                    $result_order_product = $db->createCommand($sql)->execute();
                    if( !$result_order_product ){
                        $transact->rollBack();
                        $rs = array('errNo' => 4, 'msg' => '处理订单商品失败');
                        exit(json_encode($rs));
                    }

                    //生成订单
                    $order = new Order();
                    $order->id = $order_id;
                    $order->user_id = $user_id;
                    $order->order_status = 1;
                    $order->shipping_status = 1;
                    $order->pay_status = 1;
                    $order->product_num = count($shopping_carts);
                    $order->product_fee = $product_fee;
                    $order->shipping_id = 0;
                    $order->address_id = $address_id;
                    $order->shipping_fee = 0;
                    $order->order_fee = $product_fee;//订单金额=商品总价+快递费
                    $order->pay_fee = $product_fee;
                    $order->message = $message;
                    $order->create_time = $now_time;
                    if( !$order->save(false) ){
                        $transact->rollBack();
                        $rs = array('errNo' => 5, 'msg' => '生成订单失败');
                        exit(json_encode($rs));
                    }

                    //清除购物车里已经生成订单的商品
                    $sql = "DELETE FROM `shopping_cart` WHERE `user_id`={$user_id} AND `id` IN($ids)";
                    $result_shopping_cart = $db->createCommand($sql)->execute();
                    if( !$result_shopping_cart ){
                        $transact->rollBack();
                        $rs = array('errNo' => 6, 'msg' => '处理购物车失败');
                        exit(json_encode($rs));
                    }
                    $transact->commit();

                }catch(Exception $e){
                    $transact->rollBack();
                    $rs = array('errNo' => 7, 'msg' => '生成订单失败.');
                    exit(json_encode($rs));
                }
            }while(false);
            $rs = [
                'errNo' => 0, 
                'msg' => 'success', 
                'url'=>Yii::$app->request->hostInfo.'/order/pay/'.$order_id
            ];
            exit(json_encode($rs));
        }

        //获取收货地址
        $all_address = \common\models\Address::find()->where('user_id=:user_id AND is_show=1', [':user_id'=>$user_id])->all();

        //省、市、区
        $region =  Region::find()->where(['parent_id' => 1])->all();
        $cityJson = $cache->get('address_city_json');
        if( $cityJson===false ){
            $city = array ();
            foreach ($region as $key => $val)
            {
                //市
                $id = $val->id;
                $sql = "SELECT `id`, `name` FROM `region` WHERE `parent_id` = {$id}";
                $child = $db->createCommand($sql)->queryAll();

                //区
                foreach( $child as $k=>$v ){
                    $v_id = $v['id'];
                    $sql = "SELECT `id`, `name` FROM `region` WHERE `parent_id` = {$v_id}";
                    $district = $db->createCommand($sql)->queryAll();
                    $child[$k]['id'] = $v_id;
                    $child[$k]['name'] = $v['name'];
                    $child[$k]['district'] = $district;
                }
                $city[] = [
                    'id' => $id,
                    'name' => $val->name,
                    'child' => $child
                ];
            }
            $cityJson = json_encode($city);
            $cache->set('address_cityjson', $cityJson, 60*60*24*30);
        }



        return $this->render('confirm', [
            'shopping_carts' => $shopping_carts,
            'all_address' => $all_address,
            'region' => $region,
            'cityJson' => $cityJson,
        ]);
    }

    //支付页面
    public function actionPay()
    {
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }

        //查询订单信息
        $order_id = Myhelpers::RemoveXSS(Yii::$app->request->get('id'));//订单id
        $model = Order::findOne($order_id);

        //查询订单中商品的数量和名称
        $prolist = (new \Yii\db\Query())
                ->from('order_product a')
                ->select('b.name,a.product_num')
                ->where(['a.order_id' => $order_id])
                ->leftJoin('product AS b','a.product_id = b.id')
                ->all();
        //var_dump($prolist);
        //exit;

        //查询选择的收货地址信息
        $ad = (new \Yii\db\Query())->from('address')->where(['id'=>$model->address_id])->one();
        $address['province'] = Region::findOne($ad['province'])->name;
        $address['city'] = Region::findOne($ad['city'])->name;
        $address['district'] = Region::findOne($ad['district'])->name;

        $address = $ad['name']." ".$ad['phone']." ".$address['province']." ".
                   $address['city']." ".$address['district']." ".$ad['address_detail'];
        //查询用户账户信息
        $available_money = Yii::$app->user->identity['available_money'];
        
        return $this->render('pay',[
            'model' => $model,
            'money' => $available_money,
            'address' => $address,
            'prolist' => $prolist
        ]);
    }
    //默认支付宝支付中转方法
    public function actionAlipay(){

        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }

        $user_id = Yii::$app->user->id;
        $order_id = Myhelpers::RemoveXSS(Yii::$app->request->get('id'));//订单id
        $order = Order::findOne($order_id);

        if(!$order){
            exit("Order does not exist");
        }
        $alipay = new Alipay($this->alipay_config);

        //商户订单号
        $out_trade_no = $order->id; //商户网站订单系统中唯一订单号，必填

        //订单名称
        $subject = "添品网订单号".$order->id;   //必填

        //付款金额
        $total_fee = $order->pay_fee;   //必填
        
        $body = $order->message;    //订单描述

        //商品展示地址
        $show_url = "http://".$_SERVER['HTTP_HOST']."/product/";

        //防钓鱼时间戳
        $anti_phishing_key = "";    //若要使用请调用类文件submit中的query_timestamp函数

        //客户端的IP地址
        $exter_invoke_ip = "";  //非局域网的外网IP地址，如：221.0.0.1
        
        $pay_id = Myhelpers::getOrderID(11);//生成充值id
        $recharge_id = Myhelpers::getOrderID(10);//生成充值id

        //发起请求之前给recharge、pay表添加数据
        $recharge = new Recharge();

        $recharge->id = $recharge_id;
        $recharge->user_id = $user_id;
        $recharge->relation_id = $pay_id;
        $recharge->money = $order->pay_fee;
        $recharge->poundage = 0;    //先留空，以后有需要设置
        $recharge->status = 1;      //充值中
        $recharge->bank_serial_no = ""; //充值成功之后回调填写
        $recharge->pay_type = '31';    //支付宝
        $recharge->create_time = date('Y-m-d H:i:s');
        $recharge->update_time = date('Y-m-d H:i:s');

        if( !$recharge->save(false) ){
            exit("生成充值记录失败");
        }

        $pay = new Pay();
        $pay->id = $pay_id;
        $pay->user_id = $user_id;
        $pay->money = $order->pay_fee;
        $pay->status = 1;   //未支付状态
        $pay->relation_id = $order_id;
        $pay->create_time = date('Y-m-d H:i:s');
        $pay->update_time = date('Y-m-d H:i:s');

        if( !$pay->save(false) ){
            exit("生成支付记录失败");
        }

        //建立请求
        echo $alipay->buildRequestFormHTML(array(
            "service"       => "create_direct_pay_by_user",
            "partner"       => trim($alipay->config['partner']),
            "payment_type"  => $alipay->config['payment_type'],
            "notify_url"    => $alipay->config['notify_url'],
            "return_url"    => $alipay->config['return_url'],
            "seller_id"     => $alipay->config['partner'],
            "out_trade_no"  => $out_trade_no,
            "subject"       => $subject,
            "total_fee"     => $total_fee,
            "body"          => $body,
            "show_url"      => $show_url,
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip"   => $exter_invoke_ip,
            "_input_charset"    => trim(strtolower($alipay->config['input_charset']))
        ), "post");
    }

    //Alipay同步通知返回方法
    public function actionPayreturn(){
        
        $alipay = new Alipay($this->alipay_config);
        $verify_result = $alipay->verifyCallback();
        if($verify_result) {//验证成功
            
            $out_trade_no = $_GET['out_trade_no'];  //商户订单号

            $trade_no = $_GET['trade_no'];  //支付宝交易号
            
            $trade_status = $_GET['trade_status'];  //交易状态

            $model = Order::findOne($out_trade_no);

            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                return $this->render('success',['model' =>$model]);
            }else {
                $model = "交易状态：".$_GET['trade_status'];
                return $this->render('fail',['model' =>$model]);
            }

        }else {
            //验证失败
            $model = "验证失败";
            return $this->render('fail',['model' =>$model]);
        }
    }
    //微信支付
    public function actionWeixin()
    {
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
        return $this->render('weixin');
    }
}
